package com.bootdo.api;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.dto.LoginDto;
import com.bootdo.common.request.Result;
import com.bootdo.common.request.ResultCode;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RandomValidateCodeUtil;
import com.bootdo.common.utils.TokenUtil;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
public class LoginApiController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    BootdoConfig bootdoConfig;


    @Log("登录")
    @PostMapping("/login")
    Result ajaxLogin(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        String username =loginDto.getUsername();
        String password =loginDto.getPassword();
        password =  MD5Utils.encrypt(username, password);
        UsernamePasswordToken  token1 = new UsernamePasswordToken(username, password);
        Subject subject =  SecurityUtils.getSubject();
        UserDO user =new UserDO();
        user.setPassword(password);
        user.setUsername(username);
        try {
            subject.login(token1);
            String token= TokenUtil.sign(user);
            HashMap<String,Object> hs=new HashMap<>();
            hs.put("token",token);
            return Result.success(hs);
        } catch (AuthenticationException e) {
            return Result.error(ResultCode.ERROR,"用户或密码错误");
        }
    }

}
